<template>
  <div class="classify-view">
    <van-sticky class="classify-view-header">
      <h1 @click="$router.back()" class="back">< 返回</h1>
    </van-sticky>

    <div class="Tabs">
      <van-tabs v-model:active="active">
        <van-tab
          v-for="item in ResData.brotherCategory"
          :title="item.name"
          :key="item.id"
        >
          <template #title
            ><span @click="onTabClick(item.id)">{{ item.name }}</span></template
          >
        </van-tab>
      </van-tabs>
    </div>

    <div class="classify-view-content" ref="scrollContainer">
      <div class="classify-view-content-header">
        <h2 class="classify-title">{{ ResData.currentCategory.name }}</h2>
        <p class="classify-desc">{{ ResData.currentCategory.desc }}</p>
      </div>

      <div class="classify-view-content-list">
        <div class="no-data" v-show="listData.list.length === 0">
          <p>暂无数据</p> 
        </div>
        <div class="list-item" v-for="item in listData.list" :key="item.id" @click="store.goToGoods(item.id)">
          <div class="list-item-img">
            <img :src="item.picUrl" alt="" />
          </div>

          <div class="list-item-content">
            <div class="list-item-title">
              <p>{{ item.name }}</p>
              <p>{{ item.brief }}</p>
            </div>

            <div class="list-item-price">
              <p>
                <span class="retailPrice">${{ item.retailPrice }}</span>
                <span class="counterPrice">${{ item.counterPrice }}</span>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref, reactive, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { getCategory, getList } from "@/server/api";
import { useCounterStore } from "@/stores/counter";

const store = useCounterStore()

const router = useRouter();
const active = ref(0);
const id = Number(router.currentRoute.value.params.id);
const ResData = reactive({
  brotherCategory: [],
  currentCategory: {},
  parentCategory: {},
});

const listData = reactive({
  list: [],
});

const page = ref(1);
const limit = ref(10);
const isLoading = ref(false);
const hasMore = ref(true);

// 获取滚动容器的引用
const scrollContainer = ref(null);

onMounted(async () => {
  //页面加载完成后获取数据
  const res = await getCategory(id);
  ResData.brotherCategory = res.data.brotherCategory;
  ResData.currentCategory = res.data.currentCategory;
  ResData.parentCategory = res.data.parentCategory;

  //初始化active
  active.value = ResData.brotherCategory.findIndex(
    (item) => item.id === id
  );

  // 初始加载第一页数据
  await loadData(id, 1, true);

  // 监听滚动事件
  if (scrollContainer.value) {
    scrollContainer.value.addEventListener("scroll", handleScroll);
  }
});

const onTabClick = async (newId) => {
  console.log(newId);
  const nowCategory = await getCategory(newId);
  ResData.currentCategory = nowCategory.data.currentCategory;

  // 切换分类时重置分页状态并加载第一页数据
  page.value = 1;
  hasMore.value = true; // 重置hasMore状态
  await loadData(newId, 1, true);
  if (scrollContainer.value) {
    scrollContainer.value.scrollTop = 0;
  }
};

// 封装数据加载方法
const loadData = async (currentId, currentPage = 1, isReset = false) => {
  if (isLoading.value || !hasMore.value) return;

  isLoading.value = true;
  try {
    const list = await getList({
      categoryId: currentId,
      page: currentPage,
      limit: limit.value,
    });

    // 如果是重置（如切换分类），直接替换数据
    if (isReset) {
      listData.list = list.data.list;
    } else {
      // 否则追加数据
      listData.list = [...listData.list, ...list.data.list];
    }

    // 判断是否还有更多数据
    hasMore.value = list.data.list.length >= limit.value;
    page.value = currentPage;
  } catch (error) {
    console.error("加载数据失败:", error);
  } finally {
    isLoading.value = false;
  }
};

// 基于组件容器计算
const handleScroll = () => {
  // 如果容器不存在、正在加载中或没有更多数据，直接返回
  if (!scrollContainer.value || isLoading.value || !hasMore.value) return;

  // 获取容器的滚动相关属性
  const container = scrollContainer.value;
  const scrollTop = container.scrollTop;
  const clientHeight = container.clientHeight;
  const scrollHeight = container.scrollHeight;

  // 当距离容器底部200px时加载更多
  if (scrollTop + clientHeight >= scrollHeight - 200) {
    loadData(ResData.currentCategory.id, page.value + 1);
  }
};

onUnmounted(() => {
  if (scrollContainer.value) {
    scrollContainer.value.removeEventListener("scroll", handleScroll);
  }
});
</script>

<style scoped lang="scss">
.classify-view {
  background-color: #e2e2e24d;
  height: 100%;
}
.back {
  background-color: white;
  height: 80px;
  line-height: 80px;
  padding: 0px 30px;
  color: #147ebbc0;
  font-size: 40px;
  font-weight: bold;
}
.classify-view-content {
  height: 85vh;
  overflow: hidden;
  overflow-y: auto;
}
::v-deep .van-tabs__line {
  background: red;
}
.classify-view-content-header {
  padding: 50px 0px;
  text-align: center;
}
.classify-title {
  font-size: 60px;
  margin-bottom: 30px;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif; /* 适配移动端+PC */
  font-weight: 300; /* 标题加粗，强化层级 */
  line-height: 1.2; /* 紧凑行高，贴合设计感 */
}

.classify-desc {
  font-size: 40px;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  font-weight: 300; /* 细体，区分辅助文案 */
  line-height: 1.4; /* 宽松行高，提升阅读感 */
  color: #666; /* 浅灰，弱化辅助信息 */
}
.list-item {
  height: 300px;
  display: flex;
  justify-content: start;
  gap: 60px;
  margin: 30px 0;
  background-color: white;
  > .list-item-img {
    width: 260px;
    height: 260px;
    > img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  > .list-item-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 20px 0;
    > .list-item-title {
      margin-bottom: 20px;
      > p:first-child {
        font-size: 36px;
        font-weight: bold;
        font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
        line-height: 1.2;
        margin-bottom: 10px;
      }
      > p:last-child {
        font-size: 24px;
        font-weight: 300;
        font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
        line-height: 1.6;
        color: #666;
      }
    }
    > .list-item-price {
      display: flex;
      justify-content: space-between;
      align-items: center;
      > p {
        font-size: 36px;
        font-weight: 200;
        font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
        line-height: 1.2;
        color: #ff5a5f;
        > .counterPrice {
          font-size: 24px;
          margin-left: 20px;
          text-decoration: line-through;
          color: #999;
        }
      }
    }
  }
}
.no-data {
  height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  > p{
    font-size: 42px;
    font-weight: 300;
    color: #666;
  }
}
</style>
